package com.shoulder.core.utils;

import com.nimbusds.jose.JWSObject;
import com.shoulder.core.api.ApiUser;
import com.shoulder.core.enums.HeaderEnums;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.text.ParseException;

/**
 * Copyright (c) 2024-2050 heguangchuan <596767880@qq.com>
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * <a href="http://www.apache.org/licenses/LICENSE-2.0">...</a>
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * <p>
 * 哎 太难了 没想到只是写着玩玩  却耐着性子一直写下来了
 *
 * @author 596767880@qq.com
 * @since 2024/5/10 下午5:27
 */
public class TokenUtils {

    public static ApiUser parseUser() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        return parseUser(request.getHeader(HeaderEnums.BEARER_HEADER.getCode()));
    }

    public static ApiUser parseUser(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        String authorization = token.replace("Bearer ", "");
        try {
            //实际上在这里肯定还应该做校验验签的,这里为了方便不做处理,放在 spring authorization server 自行校验
            JWSObject jwsObject = JWSObject.parse(authorization);
            return JsonUtils.json2Bean(jwsObject.getPayload().toString(), ApiUser.class);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }
}
